package com.bilibili.manage;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import com.bilibili.exception.BusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.Objects;

/**
 * 文件上传服务:将文件上传至OSS
 *
 * @author ym
 */
@Component
public class OssService {
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.bucketName}")
    private String bucketName;
    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${file.server.path}")
    private String fileServerPath;


    /**
     * 将文件上传至OSS
     *
     * @param fileName        文件名。文件名包含路径，不包含Bucket名称
     * @param fileInputStream 文件字节流
     * @return filePath用于访问文件的地址
     */
    public String uploadFile(String fileName, InputStream fileInputStream) {
        OSS ossClient = null;
        String filePath = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            PutObjectResult result = ossClient.putObject(bucketName, fileName, fileInputStream);
            filePath = fileServerPath + fileName + "?versionId=" + result.getVersionId();
        } catch (OSSException e) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "上传失败");
        } finally {
            if (!Objects.isNull(ossClient)) {
                // 关闭OSSClient。
                ossClient.shutdown();
            }
        }
        return filePath;
    }
}
